import React, {Component} from "react";
import PropTypes from "prop-types";
import {Table} from "antd";
import {routerRedux} from "dva/router";
import axios from "axios";
import lodash from "lodash";

class DataTable extends Component {
  constructor(props) {
    super(props)
    const {
      dataSource,
      pagination = {
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条`,
        current: 1,
        pageSize: 10,
        total: 100
      }
    } = props
    this.state = {loading: false, dataSource, fetchData: {}, pagination}
  }

  componentDidMount() {
    this.fetch()
  }

  componentWillReceiveProps(nextProps) {
    const staticNextProps = lodash.cloneDeep(nextProps)
    delete staticNextProps.columns
    const {
      columns,
      ...otherProps
    } = this.props
    if (!lodash.isEqual(staticNextProps, otherProps)) {
      this.props = nextProps
      this.fetch()
    }
  }

  handleTableChange = (pagination, filters, sorter) => {
    const {current, pageSize} = pagination
    const {
      route: {
        location: {pathname, query},
        dispatch
      }
    } = this.props
    dispatch(routerRedux.push({
      pathname, query: {
        ...query, page: current, size: pageSize
      }
    }))
  }

  fetch = () => {
    const {
      method = 'get',
      keyColumn = 'id',
      route: {location: {pathname, query}, dispatch},
      url
    } = this.props
    let {page, size} = query
    if (!page || !size) {
      dispatch(routerRedux.push({
        pathname, query: {
          ...query, page: page || 1, size: size || 10
        }
      }))
      return
    }
    if (size > 100) {
      size = 100
    }
    this.setState({loading: true})
    axios({url, method, params: {...query, page, size}})
    .then(({data: {rows, total}, status}) => {
      if (status == 200) {
        const {pagination} = this.state
        rows.map(row => {
          if (row) {
            if (!row.key) {
              row.key = row[keyColumn]
            }
          }
        })
        this.setState({
          loading: false,
          dataSource: rows,
          pagination: {
            ...pagination,
            total,
            current: Number(page),
            pageSize: Number(size)
          }
        })
      }
    })
  }

  render() {
    const {
      method, keyColumn, route,
      url, params,
      ...tableProps
    } = this.props
    const {loading, dataSource, pagination} = this.state
    return (<Table
      ref="DataTable"
      bordered
      loading={loading}
      onChange={this.handleTableChange}
      {...tableProps}
      pagination={pagination}
      dataSource={dataSource}/>)
  }
}

DataTable.propTypes = {
  fetch: PropTypes.object,
  rowKey: PropTypes.string,
  pagination: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.object]),
  columns: PropTypes.array,
  dataSource: PropTypes.array
}

export default DataTable
